package br.com.virtual.relatorio.model;

import java.util.Calendar;
import java.util.Map;
import java.util.TreeMap;

import br.com.virtual.base.model.VirtualModel;

public class Relatorio<T extends VirtualModel> {
	
	private Periodo periodo;
	private Double total;
	
	private Map<String, RelatorioPeriodo<T>> relatorioPeriodos;
	
	
	public Relatorio(Periodo periodo){
		
		this.init();
		this.periodo = periodo;
		
	}
	
	public void init(){
		this.relatorioPeriodos = new TreeMap<String, RelatorioPeriodo<T>>();
		this.total = 0.0;
		this.periodo = new Periodo(null, null);
	}
	
	public void addItem(T item, Calendar data, Double valorToSum){
		
		StringBuilder periodo = new StringBuilder(String.valueOf(data.get(Calendar.YEAR)));
		periodo.append("-");
		periodo.append(String.valueOf(data.get(Calendar.MONTH)));

		RelatorioPeriodo<T> relatorioPeriodo = this.relatorioPeriodos.get(periodo.toString());
		
		if( relatorioPeriodo == null )
			relatorioPeriodo = new RelatorioPeriodo<T>(periodo.toString());
		
		this.total += valorToSum;
		relatorioPeriodo.addItem(item, valorToSum);
		
		this.relatorioPeriodos.put(periodo.toString(), relatorioPeriodo);
		
	}
	
	
	/*
	 * g & s
	 * */

	public Map<String, RelatorioPeriodo<T>> getRelatorioPeriodos() {
		return relatorioPeriodos;
	}
	
	public Periodo getPeriodo(){
		return periodo;
	}
	
	public Double getTotal(){
		return total;
	}
	

	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + ((periodo == null) ? 0 : periodo.hashCode());
		result = prime
				* result
				+ ((relatorioPeriodos == null) ? 0 : relatorioPeriodos
						.hashCode());
		result = prime * result + ((total == null) ? 0 : total.hashCode());
		return result;
	}
	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		
		@SuppressWarnings("unchecked")
		Relatorio<T> other = (Relatorio<T>) obj;
		if (periodo == null) {
			if (other.periodo != null)
				return false;
		} else if (!periodo.equals(other.periodo))
			return false;
		if (relatorioPeriodos == null) {
			if (other.relatorioPeriodos != null)
				return false;
		} else if (!relatorioPeriodos.equals(other.relatorioPeriodos))
			return false;
		if (total == null) {
			if (other.total != null)
				return false;
		} else if (!total.equals(other.total))
			return false;
		return true;
	}
	@Override
	public String toString() {
		return "Relatorio [periodo=" + periodo + ", total=" + total
				+ ", relatorioPeriodos=" + relatorioPeriodos + "]";
	}
	
}
